// 跳转路径自定义
interface Route {
  name: string,
  path: string,
  children?: Route[]
}

const routes = [
  {
    name: "/login",
    path: "/pages/login/index",
    children: [{
      name: "/mobie",
      path: "/pages/login/mobie/index"
    }]
  },
  {
    name: '/home',
    path: '/pages/index/index',
    children: [
      {
        name: '/bannerDetail',
        path: '/home/pages/bannerDetail/index'
      },
      {
        name: '/goodDetail',
        path: '/home/pages/goodDetail/index'
      },
      {
        name: "/search",
        path: '/home/pages/search/index'
      }
    ]
  },
  {
    name: '/mine',
    path: "/pages/mine/mine",
    children: [{
      name: "/ani",
      path: "/mine/pages/animation/index"
    }, {
      name: '/components',
      path: "/mine/pages/components/index"
    }, {
      name: '/componentsImage',
      path: "/mine/pages/components/imageComponent/index"
    }, {
      name: '/webView',
      path: "/mine/pages/components/webView/index"
    }, {
      name: '/skyline',
      path: "/mine/pages/skyline/index"
    }]
  }
]

class Router {
  private routes: Route[] = [];
  private pathReg = /\/\w+/g
  constructor() {
    this.routes = routes;
  }

  public push(name: string, data?: any) {
    const route = this.retrievePath(name)
    if (data) {
      const queryStr = Object.keys(data).map(k => `${k}=${data[k]}`).join('&');
      wx.navigateTo({
        url: `${route.path}?${queryStr}`,
      });
    } else {
      //   console.log('route path:', route.path)
      wx.navigateTo({
        url: `${route.path}`,
      });
    }
  }

  public reLaunch(name: string) {
    const route = this.retrievePath(name)
    wx.reLaunch({
      url: `${route.path}`
    })
  }

  public switchTab(name: string) {
    const route = this.retrievePath(name)
    wx.switchTab({
      url: `${route.path}`
    })
  }

  public back() {
    wx.navigateBack()
  }

  public redirectTo(name: string) {
    const route = this.retrievePath(name)
    wx.redirectTo({
      url: `${route.path}`
    })
  }

  private retrievePath(name: string): Route {
    const names = name.match(this.pathReg)
    if (!names) throw new Error("route path parse error");
    const route = this.retrieve(names, { name: '', path: '' }, this.routes)
    if (!route) throw new Error(`not found route path ${name}`)
    return route
  }

  private retrieve(names: string[], route: Route, routes: Route[] | undefined): Route | undefined {
    if (!names || names.length == 0) return route
    if (!routes) return

    const name = names.shift()
    let curr_route;
    for (let i = 0; i < routes.length; i++) {
      const r = routes[i]
      if (r.name === name) {
        curr_route = r
        break
      }
    }
    if (!curr_route) return
    return this.retrieve(names, curr_route, curr_route.children)
  }
}

export default function createRouter() {
  return new Router()
}